//
//  XQLoginController.swift
//  Spark Peso
//
//  Created by 小琦 on 2025/2/4.
//

import UIKit

let kXQPhoneToast = "Please enter your phone number"

let kXQCodeToast = "Please enter the verification code"

let kXQProtocolToast = "Please read and agree to the Privacy Policy"

class XQLoginController: XQBaseController {
    
    private var phoneValue : String? = ""
    private var codeValue : String? = ""
    
    private lazy var bgImageView : UIImageView = {
       let imageView = UIImageView()
        imageView.image = UIImage(named: "login_bg")
        imageView.isUserInteractionEnabled = true
        imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(bgImageClick)))
        return imageView
    }()
    
    private lazy var logoImageView : UIImageView = {
        let logoImageView = UIImageView()
        logoImageView.image = UIImage(named: "AppIcon")
        logoImageView.layer.cornerRadius = 10
        logoImageView.layer.masksToBounds = true
        return logoImageView
    }()
    private lazy var titleImageView : UIImageView = {
        let titleImageView = UIImageView()
        titleImageView.image = UIImage(named: "login_title")
        return titleImageView
    }()
    
    private lazy var bottomView : UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()
    
    private lazy var phoneView : XQLoginPhoneView = {
        let view = XQLoginPhoneView()
        view.textFielHandle = {[weak self] text in
            guard let srongify = self else {return}
            srongify.phoneValue = text
        }
        return view
    }()
    
    private lazy var codeView : XQLoginCodeView = {
        let view = XQLoginCodeView()
        view.textFielHandle = {[weak self] text in
            guard let srongify = self else {return}
            srongify.codeValue = text
        }
        view.sendHandle = {[weak self] in
            guard let srongify = self else {return}
            srongify.sendCodeClick()
        }
        return view
    }()
    
    private lazy var vozBtn : UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("VOZ?", for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 14,weight: .medium)
        btn.setTitleColor(.xq_black, for: .normal)
        btn.addTarget(self, action: #selector(vozClick), for: .touchUpInside)
        return btn
    }()
    
    private lazy var protocolView : XQLoginProtocolView = {
        let view = XQLoginProtocolView()
        view.prefixStr = "I have read and agree with "
        view.suffixStr = "<Privacy agreement>"
        view.protocolClickHandle = {[weak self] in
            guard let srongify = self else {return}
            srongify.protocolClick()
        }
        return view
    }()
    
    private lazy var loginBtn : UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("Log in", for: .normal)
        btn.backgroundColor = .mainTextColor
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20)
        btn.layer.cornerRadius = 30
        btn.addTarget(self, action: #selector(clickLogin), for: .touchUpInside)
        return btn
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        makeNav()
        makeUI()
        makeConstraints()
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        bottomView.setRoundCorners([.topLeft,.topRight], radius: 30)
    }
    
    private func makeNav() {
        self.navTitle = "Sign in"
        self.navTitleColor = .white
    }
    
    private func makeUI() {
        self.view.insertSubview(self.bgImageView, belowSubview: self.navigationBar)
        self.bgImageView.addSubview(self.logoImageView)
        self.bgImageView.addSubview(self.titleImageView)
        self.bgImageView.addSubview(self.bottomView)
        self.bottomView.addSubview(self.phoneView)
        self.bottomView.addSubview(self.codeView)
        self.bottomView.addSubview(self.vozBtn)
        self.bottomView.addSubview(self.protocolView)
        self.bottomView.addSubview(self.loginBtn)
    }
    
    private func makeConstraints() {
        self.bgImageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        self.logoImageView.snp.makeConstraints { make in
            make.top.equalTo(UIDevice.xq_statusHeight() + 60)
            make.left.equalTo(16)
            make.width.height.equalTo(48)
        }
        self.titleImageView.snp.makeConstraints { make in
            make.top.equalTo(self.logoImageView.snp.bottom).offset(16)
            make.left.equalTo(self.logoImageView.snp.left)
        }
        self.bottomView.snp.makeConstraints { make in
            make.top.equalTo(self.titleImageView.snp.bottom).offset(41)
            make.left.right.bottom.equalTo(0)
        }
        self.phoneView.snp.makeConstraints { make in
            make.top.equalTo(38)
            make.left.equalTo(24)
            make.right.equalTo(-24)
            make.height.equalTo(58)
        }
        self.codeView.snp.makeConstraints { make in
            make.top.equalTo(self.phoneView.snp.bottom).offset(18)
            make.left.equalTo(24)
            make.right.equalTo(-24)
            make.height.equalTo(58)
        }
        self.vozBtn.snp.makeConstraints { make in
            make.top.equalTo(self.codeView.snp.bottom).offset(16)
            make.right.equalTo(-24)
        }
        self.protocolView.snp.makeConstraints { make in
            make.bottom.equalTo(-50)
            make.left.equalTo(29)
            make.right.equalTo(0)
        }
        self.loginBtn.snp.makeConstraints { make in
            make.bottom.equalTo(self.protocolView.snp.top).offset(-20)
            make.left.equalTo(18)
            make.right.equalTo(-18)
            make.height.equalTo(54)
        }
    }
    
    private func sendCodeClick() {
        
        if (self.phoneValue?.count == 0) {
            XQHud.showToast(message: kXQPhoneToast)
            return
        }
        
        setStartT()
        
        let params: [String: String] = ["fundamental": self.phoneValue!]
        
        XQHud.showLoading(controller: self)
        XQNetworkManager.shared.postRequest(url: "/figures/question", parameters: params) {[weak self] response, error in
            guard let srongify = self else {return}
            XQHud.hideLoading(controller: srongify)
            if (response?.object == 0) {
                srongify.codeView.sendBtn.stop()
                srongify.codeView.sendBtn.start()
                srongify.codeView.becomeResponder()
                
                XQHud.showToast(message: response?.patients ?? "Send Success")
            }else {
                XQHud.showToast(message: response?.patients ?? "Network Connection Error")
            }
        }
    }
    
    private func protocolClick() {
        let str = XQInitManager.shared.loginProtocol()
        if str.isEmpty {return}
        
        XQRouteTool.jumpController(controller: self, url: str)
    }
    
    private func setStartT() {
        if (self.startTime == 0) {
            self.startTime = XQTimeTool.nowTime()
        }
    }
    
    private func setEndT() {
        self.endTime = XQTimeTool.nowTime()
    }
    
    private func notifyRisk() {
        setEndT()
        
        XQAnalysisManager.shared.notifyRisk(numberType: "1", longitude: self.longitude, latitude: self.latitude, startT: self.startTime, endT: self.endTime, orderId: "")
    }
}

extension XQLoginController {
    
    @objc private func vozClick() {
        if (self.phoneValue?.count == 0) {
            XQHud.showToast(message: kXQPhoneToast)
            return
        }
        
        setStartT()
        
        let params: [String: String] = ["fundamental": self.phoneValue!]
        
        XQHud.showLoading(controller: self)
        XQNetworkManager.shared.postRequest(url: "/figures/technician", parameters: params) {[weak self] response, error in
            guard let srongify = self else {return}
            XQHud.hideLoading(controller: srongify)
            if (response?.object == 0) {
                srongify.codeView.becomeResponder()
                XQHud.showToast(message: response?.patients ?? "Voz Send Msg Success")
            }else {
                XQHud.showToast(message: response?.patients ?? "Network Connection Error")
            }
        }
    }
    
    @objc private func clickLogin() {
        if (self.phoneValue?.count == 0) {
            XQHud.showToast(message: kXQPhoneToast)
            return
        }
        if (self.codeValue?.count == 0) {
            XQHud.showToast(message:kXQCodeToast)
            return
        }
        if (!self.protocolView.radioBtn.isSelected) {
            XQHud.showToast(message: kXQProtocolToast)
            return
        }
        
        let params: [String: String] = ["individual": self.phoneValue!,"annual":self.codeValue!]
        
        XQHud.showLoading(controller: self)
        XQNetworkManager.shared.postRequest(url: "/figures/object", parameters: params) {[weak self] response, error in
            guard let srongify = self else {return}
            XQHud.hideLoading(controller: srongify)
            if (response?.object == 0) {
                if let procedure = response?.procedure {
                    if let sessionId = procedure["myriad"] {
                        if (sessionId is String && !(sessionId as! String).isEmpty) {
                            XQNetworkManager.shared.setSessionId(sessionId: sessionId as? String)
                        }
                    }
                }
                srongify.notifyRisk()
                srongify.navigationController?.popViewController(animated: true)
            }else {
                XQHud.showToast(message: response?.patients ?? "Network Connection Error")
                self?.codeView.clearNumber()
            }
        }
    }
    
    @objc private func bgImageClick() {
        self.view.endEditing(true)
    }
}


